package com.tech.koufu.ui.activity.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.EntrustStock;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.adapter.TradeAdapter;
import com.tech.koufu.ui.view.BaseSimpleFragment;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable; 
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 当日历史记录
 * @author jl_luo
 *
 */
public class TradeDateFragment extends BaseSimpleFragment {
	private static final String TAG = TradeDateFragment.class.getName();
	private View rootView;
	private int page = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView; 
	private TradeAdapter mAdapter;
	private String userid,groupid;
	private MyApplication myApp;
	private Context context;
	private ArrayList<EntrustStock> datas;

	private RequestQueue mQueue;  
	CookieStringRequest stringRequest;
	private String digitalid;

	public static TradeDateFragment newInstance(int index,String userid,String groupid,String digitalid) {
		TradeDateFragment hf = new TradeDateFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("index", index);
		bundle.putString("userid", userid);
		bundle.putString("groupid", groupid);
		bundle.putString("digitalid", digitalid);
		hf.setArguments(bundle); 
		return hf;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {Log.d(TAG, "~~~~~onCreateView~~~~~~");
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.lv_list_competition, container, false);   
			myApp = (MyApplication) getActivity().getApplication();
			context = getActivity().getApplicationContext();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		initView();
		return rootView; 
	}

	private void initView() { 
		mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);

		mAdapter = new TradeAdapter(context);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
		Bundle bundle = getArguments();
		if(bundle!=null){
			userid = bundle.getString("userid");
			groupid = bundle.getString("groupid");
			digitalid = bundle.getString("digitalid");
			Log.d(TAG, userid+",groupid="+groupid+",digitalid="+digitalid);
		}
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
		super.onActivityCreated(savedInstanceState);
		initData();
	}
	private void initData(){
		datas = new ArrayList<EntrustStock>();
		mQueue = Volley.newRequestQueue(context);  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }   
				loadHisEntrust();
			}
		}); 
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
	}
	
	private void loadHisEntrust(){
		String url = Statics.URL_PHP+Statics.IF_entrust;
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {  
				if(!TextUtils.isEmpty(response)){ Log.w("tt", response.trim());
					try {  
						JSONObject obj = new JSONObject(response.trim());
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONArray arry = obj.optJSONArray("data");
							if(arry!=null){
								int length = arry.length();
								for(int i=0;i<length;i++){
									JSONObject o = arry.optJSONObject(i);
									EntrustStock userStocks = new EntrustStock(); 
									 userStocks.stockName = o.optString("stock_name");
									 userStocks.stockId =  o.optString("stock_code");
									 userStocks.price = o.optString("price");
									 userStocks.time = o.optString("date");
									 userStocks.amount = o.optString("amount");
									 userStocks.entrustBs = o.optString("entrust_bs");
									 userStocks.status = o.optString("status");
									 datas.add(userStocks);
								}
								if(null!=datas && datas.size()>0){
									mAdapter.datas = datas;
									mAdapter.notifyDataSetChanged(); 
								}  
							}else{
								page--;
							}
						}else{  
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				mPullToRefreshListView.onRefreshComplete();
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page+"");    
				params.put("userID", userid);
				return params;
			}
		}; 
		stringRequest.setCharset("GBK");
		stringRequest.setHeader(myApp.phpsessid);
		mQueue.add(stringRequest);
	}
	
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
//			Toast.makeText(context, position + "," + id, Toast.LENGTH_SHORT).show();
		}
	};
}
